<!--
 * 介绍:列表组件
-->
<script lang="ts" setup generic="F extends RequestList.Api">
import {
  useRlistRef,
  Emits,
  Props as RlistPorps,
} from "@@/components/rework/Rlist/index";
import { useRequestList, RequestList } from "@@/hooks/useRequestList";
import { TransitionGroup, Suspense } from "vue";
import { extendsClistSlots } from "./index";

export interface Props<F> extends RlistPorps {
  /**api接口 */
  api: F;
  /**发起请求前 */
  reqBefore?: RequestList.RequestBefore<F>;
  transitionGroup?: string | false;
  extraParams?: any[];
  params?: Partial<RequestList.ApiParams<F>[0]>;
  isOnePage?: boolean;
}

const props = withDefaults(defineProps<Props<F>>(), {
  minHeight: "50vh",
  pullRefresh: true,
  transitionGroup: "CrequestList",
  offsetTop: "110rem",
});

const emit = defineEmits<Emits>();
function load() {
  emit("load");
  request();
}
/**监听下拉刷新 */
async function onRefresh() {
  emit("refresh");
  pullDownStart();
  const res = await rerequest();
  if (res.type === "error") return pullDownFail();
  pullDownSuccess();
}
/**下拉刷新成功 */
function pullDownSuccess() {
  RlistRef.value?.pullDownSuccess();
}
/**下拉刷新开始 */
function pullDownStart() {
  RlistRef.value?.pullDownStart();
}
/**下拉刷新失败 */
function pullDownFail() {
  RlistRef.value?.pullDownFail();
}
const {
  data,
  state,
  res,
  request,
  rerequest,
  stateEnd,
  stateErr,
  stateLoading,
  stateNull,
  stateNext,
} = useRequestList(props.api, props.isOnePage, {
  requestBefore: props.reqBefore,
  returnExtraParams: () => props.extraParams || [],
  returnReq: () => props.params || {},
});
/**暴露分页hooks */
defineExpose({
  rerequest,
  state,
  data,
  res,
  stateEnd,
  stateErr,
  stateLoading,
  stateNull,
  stateNext,
});

const RlistRef = useRlistRef();
</script>
<template>
  <Rlist
    ref="RlistRef"
    :="props"
    :state="state"
    @load="load"
    @refresh="onRefresh"
  >
    <slot :list="data">
      <!-- 循环渲染 -->
      <div class="auto-MT-sm CrequestList_default">
        <component
          :is="props.transitionGroup ? TransitionGroup : Suspense"
          :name="props.transitionGroup || undefined"
        >
          <slot
            v-for="(item, index) in data"
            name="item"
            :item="item"
            :index="index"
          >
          </slot>
        </component>
      </div>
    </slot>
    <template #[slotKey] v-for="slotKey in extendsClistSlots">
      <slot :name="slotKey"></slot>
    </template>
  </Rlist>
</template>

<style lang="scss" scoped>
.CrequestList {
  .CrequestList_default {
    margin-bottom: var(--gap-md);
  }
}
</style>
